<?php
namespace App\Services;

class MysqlPdoService
{

    private static $instance,$connect;
    public function __construct()
    {
        $this->connection = $this->connection();
    }

    static public function instance()
    {
        if (! self::$instance instanceof self)
        self::$instance = new self();

        return self::$instance;
    }

    //链接mysql
    public function connection()
    {
        $dbms='mysql';     //数据库类型
        $host='127.0.0.1'; //数据库主机名
        $dbName='r';    //使用的数据库
        $user='root';      //数据库连接用户名
        $pass='asds';          //对应的密码
        $dsn="$dbms:host=$host;dbname=$dbName;port=3308";
        try {
            $dbh=new \PDO($dsn,$user,$pass);
            $dbh->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION);
            return $dbh;
        } catch (\PDOException $e) {
            die ("Error!: " . $e->getMessage() . "<br/>");
        }

    }

    //执行原生sql
    public function select($sql)
    {

    }

    //关闭mysql
    public function colse()
    {

    }

    protected $table;
    public function table($table)
    {
        $this->table = $table;
        return $this;
    }
    public function save(array $data)
    {
        $fields = array_keys($data);
        $fields = $this->arrToString($fields,"`");
        $values = array_values($data);
        $values = $this->arrToString($values,"'");
      //  $sql = 'select * from novel limit 1';
        $sql = "INSERT INTO novel ($fields) VALUES($values)";
        $sth = $this->connection->prepare($sql);
        $sth->execute();
    }

    public function arrToString($datas,$symbol)
    {
        $str = '';
        foreach ($datas as $data) {
            $str .= $symbol.$data.$symbol.',';
        }
        $str = substr($str,0,-1);
        return $str;
    }





}
